import json
import time

reference = {}

def key_present(reference, subject):
  try:
    reference[subject]
  except KeyError, err:
    print subject + " is not in this dictionary."
    return False
  return True

def lookup_subject(reference, subject, enumeration=False, time=False):
  if key_present(reference, subject) == False:
    return

  for i in range(len(reference[subject])):
    note = reference[subject][i][0]
    if time == True:
      note = reference[subject][i][1] + ":  " + note
    if enumeration == True:
      note = str(i) + ": " + note
    print note

def remove_subject(reference, subject):
  if key_present(reference, subject) == False:
    return

  temp_reference = reference
  del temp_reference[subject]
  return temp_reference

def export_json(reference, filename="temp.json"):
  output_file = open(filename, 'w')
  json.dump(reference, output_file, indent=2)
  output_file.flush()
  output_file.close()

def import_json(reference, filename):
  try:
    input_file = open(filename, 'r').read()
    reference = json.loads(input_file)
    return reference
  except IOError, err:
    print filename + " does not exist."
    return
  except ValueError, err:
    print filename + " does not appear to be a JSON file."

def new_note(reference, subject):
  try:
    reference[subject]
  except KeyError, err:
    reference[subject] = []

  while True:
    try:
      message = raw_input("Enter a note, or :h for help:\n")
    except EOFError, err:
      return
    if message == ":q":
      return
    if message == ":h":
      print ":q                 gives the chance to change the subject"
    elif message == "":
      pass
    else:
      reference[subject].append([message, time.asctime()])

def new_subject(reference):
  try:
    subject = raw_input("Enter a subject, or :h for help: ")
  except EOFError, err:
    print ""
    return False

  if subject == "/":
    for item in reference.keys():
      print item
  elif subject[0] == "/" and len(subject) > 1:
    subject = subject[1:]
    lookup_subject(reference, subject, enumeration=True)
  elif subject == "export":
    export_json(reference)
  elif subject[:6] == "export" and len(subject) > 6:
    export_json(reference, subject[7:])
  elif subject[:6] == "import" and len(subject) > 6:
    reference = import_json(reference, subject[7:])
  elif subject[:6] == "remove" and len(subject) > 6:
    del reference[subject[7:]]
  elif subject == ":q":
    return False
  elif subject == ":h":
    print "subject              prints a list of the available subjects."
    print "export               exports to the file \"temp.json\""
    print "export [filename]    exports to the given filename"
    print "import [filename]    imports from the given filename."
    print "remove [term]        removes all notes under the given term"
    print "/[term]              returns all notes under the given term."
    print ":q                   quits the program."
  elif subject == "":
    pass
  else:
    subject = subject.lower()
    new_note(reference, subject)
  return True

def entry(reference, filename="test.json"):
  decision = True
  while decision == True:
    decision = new_subject(reference)

export_json(reference, "temp.json")
reference = import_json(reference, "temp.json")
entry(reference)
